package com.hmdp.utils;


import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 *自定义redis分布式锁
 *锁误删：相同业务共用一个锁，并发下，当前业务还未结束，由于各种原因，导致锁被其他线程释放，数据会做多次修改
 * 解决：在释放锁时判断是否是当前线程(2个操作需要原子性，否则还是可能发生锁误删)
 * 总：redis实现分布式锁思路：获取锁：set nx ex； 释放锁：判断线程是否为自己，再删
 */
public class SimpleRedisLock implements ILock {


    private String name;    //锁名称，不同业务不同锁
    private StringRedisTemplate stringRedisTemplate;

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";    //

    //释放锁脚本类
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        //锁value
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        //获取锁  key:value = lock:? : uuid-threadId
        Boolean success = stringRedisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);  //拆箱，可能发生空指针
    }

    /**
     * 释放锁
     */
    @Override
    public void unlock() {

        // execute(RedisScript<T> script, List<K> keys, Object... args)
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),
                Thread.currentThread().getId()
                );

        //stringRedisTemplate.delete(KEY_PREFIX + name);
    }


    /*@Override
    public void unlock() {
        //获取线程标识
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        if (threadId.equals(id)){
            stringRedisTemplate.delete(KEY_PREFIX + name);
        }
    }*/
}
